package io.github.rascaler.dcenter.context;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 获取上下文环境
 *
 * Created by wurenqing on 2017/3/20.
 */
@Component
public class ApplicationContextUtils implements ApplicationContextAware {
    private static ApplicationContext context;

    public static ApplicationContext getApplicationContext() {
        return context;
    }

    public static <T> List<T> getBeansByClass(Class<T> c) {
        Map<String, T> map = context.getBeansOfType(c);
        List<T> beans = new ArrayList<T>();
        for (Map.Entry<String, T> entry : map.entrySet()) {
            beans.add(entry.getValue());
        }
        return beans;
    }

    public static <T> T getBeanByClass(Class<T> c) {
        Map<String, T> map = ApplicationContextUtils.getApplicationContext().getBeansOfType(c);
        List<T> beans = new ArrayList<T>();
        for (Map.Entry<String, T> entry : map.entrySet()) {
            beans.add(entry.getValue());
        }
        return beans.get(0);
    }

    public static String getProperty(String propertyName) {
        return context.getEnvironment().getProperty(propertyName);
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException {
        return (T) context.getBean(name);
    }

    public static String getActiveProfile() {
        return context.getEnvironment().getActiveProfiles()[0];
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

}
